﻿/*----------------------------------------------------------------
//  <copyright file="ServiceCollectionExtensions.cs" company="MicroCloud@151504200868">
//      Copyright © 2020-2024 MicroCloud Corporation, All rights reserved.
//  </copyright>
//  <site>https://gitee.com/chenmm123/microclouds</site>
//  <last-editor>cmm</last-editor>
//  <last-date>2022-11-15 12:52</last-date>
//----------------------------------------------------------------*/

namespace MicroCloud.Authorization
{
    #region "ServiceCollection扩展"
    /// <summary>
    /// ServiceCollection扩展
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        #region "扩展方法"
        #region "添加名称为 MicroCloudPolicy 的授权策略"
        /// <summary>
        /// 添加名称为 MicroCloudPolicy 的授权策略
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddFunctionAuthorizationHandler(this IServiceCollection services)
        {
            MicroCloudOptions options = services.GetMicroCloudOptions();

            //services.AddAuthorization();
            services.AddAuthorization(opts =>
            {
                opts.AddPolicy(AuthorizationRequirement.Policy, policy =>
                {
                    policy.Requirements.Add(new AuthorizationRequirement());
                    //policy.AuthenticationSchemes.AddIf(JwtBearerDefaults.AuthenticationScheme, options.Jwt?.Enabled == true);
                    //policy.AuthenticationSchemes.AddIf(CookieAuthenticationDefaults.AuthenticationScheme, options.Cookie?.Enabled == true);
                });
            });
            services.AddSingleton<IAuthorizationHandler, FunctionAuthorizationHandler>();

            return services;
        }
        #endregion
        #region "应用功能权限授权"
        /// <summary>
        /// 应用功能权限授权
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseFunctionAuthorization(this IApplicationBuilder app)
        {
            app.UseAuthorization();

            IServiceProvider provider = app.ApplicationServices;

            IModuleHandler moduleHandler = provider.GetRequiredService<IModuleHandler>();
            moduleHandler.Initialize();

            IFunctionHandler functionHandler = provider.GetRequiredService<IFunctionHandler>();
            functionHandler.RefreshCache();

            IFunctionAuthCache functionAuthCache = provider.GetRequiredService<IFunctionAuthCache>();
            functionAuthCache.BuildRoleCaches();

            return app;
        }
        #endregion

        #endregion

    }
    #endregion

}
